// Widgets/Personals/Friends/Friends.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetInfo , queryPetMatchChatInfo } from '../../../api/pet';
import { getIMRecentContact , getIMroammsg , getIMProfile } from '../../../api/chat';
import { throttle , formatTime } from '../../../utils/util';
const regeneratorRuntime = require('../../../common/runtime');

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    screenHeight: wx.getSystemInfoSync().screenHeight,
    CustomBar: app.globalData.CustomBar,
    tabbarHeight: wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom + 60,
    petList: [], // 宠物列表
    pet: {}, // 选择的宠物
    chatActive: 0,
    page: 0,
    dataList: [],
    TimeStamp: 0, // 拉取普通会话的起始时间
    StartIndex: 0, // 拉取普通会话的起始位置
    scrollHeight: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    refresher: false,
    longitude: '',
    latitude: '',
  },
  lifetimes: {
    attached: function() {
      let _this = this;
      // 在组件实例进入页面节点树时执行
      console.log('交友模块')
      // wx.createSelectorQuery().select('.scrollList').boundingClientRect(res => {
      //   console.log(res,'scroll')
      //   _this.setData({
      //     scrollHeight: res.height,
      //   })
      // }).exec();
      this.setData({
        longitude: wx.getStorageSync('longitude'),
        latitude: wx.getStorageSync('latitude'),
      })
      this.getUserPet();
      this.getChatMate();
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 加载更多数据
    onLoadMore: throttle(function(){
      console.log('上拉加载')
      if(this.data.isReachBottom){
        if(this.data.chatActive == '0'){
          this.getChatMate();
        }else{
          this.getChatUser();
        }
      }
    },500),
    onPullDownRefresh: function(){
      let _this = this;
      _this.setData({
        page: 0,
        StartIndex: 0,
        TimeStamp: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      if(this.data.chatActive == '0'){
        this.getChatMate();
      }else{
        this.getChatUser();
      }
      setTimeout(()=>{
        wx.stopPullDownRefresh({
          success: (res) => {
            console.log(res,'刷新成功')
            _this.setData({
              refresher: false
            })
            wx.showToast({
              title: '刷新成功',
              icon: 'none',
            })
          },
        })
      },1500)
    },
    // 切换宠物
    petChange(event){
      console.log(event.detail,'切换宠物')
      const { petList } = this.data;
      this.setData({
        pet: petList[event.detail.current],
        StartIndex: 0,
        TimeStamp: 0,
      })
      if(this.data.chatActive == '1'){
        this.getChatUser();
      }
    },
    // 获取宠物列表信息
    getUserPet(){
      let _this = this;
      queryPetInfo({userId: wx.getStorageSync('userId')})
      .then(res => {
        if(res.success){
          _this.setData({
            petList: res.data.content,
          })
          if(res.data.content.length > 0){
            _this.setData({
              pet: res.data.content[0],
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 切换聊天
    chatChange(e){
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      this.setData({
        chatActive: item,
        page : 0,
        StartIndex: 0,
        TimeStamp: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
        dataList: [],
      })
      if(this.data.chatActive == '0'){
        this.getChatMate();
      }else{
        this.getChatUser();
      }
    },
    // 获取匹配聊天列表
    getChatMate(){
      let _this = this;
      queryPetMatchChatInfo({page: _this.data.page,queryLatitude: _this.data.latitude,queryLongitude: _this.data.longitude})
      .then(res => {
        if(res.success){
          var list = this.data.dataList;
          if(_this.data.page == 0){
            list = res.data.content;
          }else{
            list = list.concat(res.data.content);
          }
          _this.setData({
            dataList: list,
            total: res.data.totalElements,
            page: _this.data.page+1,
          })
          if(_this.data.page * 10 >= res.data.totalElements){
            _this.setData({
              isReachBottom: false,
              noMore: true,
              loading: false,
              loadingFailed: false,
            })
          }else{
            _this.setData({
              isReachBottom: true,
              noMore: false,
              loading: false,
              loadingFailed: false,
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 获取我的聊天
    getChatUser(){
      let _this = this;
      getIMRecentContact({From_Account: _this.data.pet.id,TimeStamp: _this.data.TimeStamp,StartIndex: _this.data.StartIndex})
      .then(async res => {
        if(res.success){
          var list = [];
          var arr = [];
          for (let index = 0; index < res.data.SessionItem.length; index++) {
            const item = res.data.SessionItem[index];
            var userIMProfile = await _this._getIMProfile({To_Account: item.To_Account});
            if(userIMProfile.UserProfileItem.length > 0 && userIMProfile.UserProfileItem[0].ProfileItem.length > 0){
              item.nickname = userIMProfile.UserProfileItem[0].ProfileItem[0].Value;
              if(userIMProfile.UserProfileItem[0].ProfileItem.length > 2){
                var petParams =  userIMProfile.UserProfileItem[0].ProfileItem[1].Value.split(',');
                item.birthDate = petParams[0];
                item.weight = petParams[1];
                item.breedName = petParams[2];
                item.sex = petParams[3];
                item.sterilization = petParams[4];
                item.id = item.To_Account;
                item.imageUrl =  userIMProfile.UserProfileItem[0].ProfileItem[2].Value;
              }else{
                item.imageUrl =  userIMProfile.UserProfileItem[0].ProfileItem[1].Value;
              }
              
            }
            var msg = await _this._getIMroammsg({Peer_Account: item.To_Account});
            item.lastMsg = '';
            if(msg.MsgList.length > 0 && msg.MsgList[0].MsgBody.length > 0){
              item.lastMsg = msg.MsgList[0].MsgBody[0].MsgContent.Text
              item.LastMsgTime = formatTime(msg.LastMsgTime * 1000,'Y-M-D')
            }
            console.log(item,'item')
            arr.push(item);
          }
          if(_this.data.StartIndex != 0){
            list = _this.data.dataList;
            list = list.concat(arr);
          }else{
            list = arr;
          }
          _this.setData({
            dataList: list,
            StartIndex: res.data.StartIndex,
            TimeStamp: res.data.TimeStamp,
          })
          if(res.data.CompleteFlag == 1){
            _this.setData({
              isReachBottom: false,
              noMore: true,
              loading: false,
              loadingFailed: false,
            })
          }else{
            _this.setData({
              isReachBottom: true,
              noMore: false,
              loading: false,
              loadingFailed: false,
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 获取IM用户信息
    _getIMProfile({To_Account}){
      return new Promise((resolve,reject) => {
        getIMProfile({To_Account: To_Account,})
        .then(res => {
          if(res.success){
            resolve(res.data);
          }else{
            reject(res.errMessage);
          }
        })
      })
    },
    // 获取IM历史记录
    _getIMroammsg({Peer_Account}){
      let _this = this;
      var nowTime = (new Date().getTime() / 1000).toFixed(0);
      console.log(nowTime,'nowTime')
      return new Promise((resolve,reject) => {
        getIMroammsg({Operator_Account: _this.data.pet.id,Peer_Account: Peer_Account,MaxCnt: 1,MinTime: '0',MaxTime: nowTime})
        .then(res => {
          if(res.success){
            resolve(res.data);
          }else{
            reject(res.errMessage);
          }
        })
      })
    },
    // 申请配对
    applyMatings(event){
      let _this = this;
      console.log(event,'event')
      console.log(_this.data.pet,'pet')
      if(!_this.data.pet.id){
        wx.showToast({
          title: '请先添加宠物，再进行操作',
          icon: 'none',
        });
        return;
      }
      wx.navigateTo({
        url: `${event.detail.url}?item=${event.detail.item}&petId=${_this.data.pet.id}`,
      })
    },
  }
})